/**
 * @ author: 汪孟苹
 */
define(["jquery", "bbcare", "oms_config/root", "fu/app/comm/comm",
    "scprit/followup/app/question/question.servers.js"], function ($, $bb, $root, $comm, $questionServers) {
    var servers = {}
    /**
     * 获取url地址,当前用户
     */
    var URL = $bb.baseUrl("followup")
    var URL2 = $bb.baseUrl("imgCollection")
    var sessinonUserName = JSON.parse($bb.getSessionStorage("account")).alias
    var global_followupGuidance = false // 打印需要


    /**
     * 根据前一个页面传递过来的参数(患者id、实例id、任务id[可无，看情况])，获取患者信息
     */
    var getParams = function (data, params) {
        params.followQueueId = data.QueueSchemeInfo.queueId
        params.queuename = data.QueueSchemeInfo.queueName
        params.patientName = data.PatientInfo.userName
        params.gender = data.PatientInfo.gender
        var imgSrc = params.gender == 'F' ? "girl" : "boy"
        params.imgSrc = "page/followup/imgs/comm/" + imgSrc + ".png"
        params.birthday = data.PatientInfo.birthday
        params.expectedDay = data.PatientInfo.expectedDay
        params.pregnancyDay = data.PatientInfo.pregnancyDay
    }
    servers.getPageParams = function () {	// 目前只需要传患者id和患者实例id
        var params = $bb.getPageParams()
        this.getRevisedInfoParams(params, null, getParams)
        return params
    }
    /**
     * 根据患者id和患者实例id，获取患者患者信息(队列名称、队列id、患者名称、性别)
     */
    servers.getRevisedInfoParams = function (params, curInfo, callback, paramsRecord) {
        $bb.ajax({
            url: URL + "followup/service/patient/patientInfoQueryByPtId",
            data: JSON.stringify({
                data: {
                    "patientId": params.patientId,
                    "ptSchemeId": params.patientSchemeId,
                }
            }),
            success: function (data) {
                if (data.success) {
                    callback(data.data, params, curInfo, paramsRecord)
                } else {
                    $bb.toastShow(data.msg ? data.msg : "查询患者信息出错！")
                }
            }
        })
    }
    /**
     * 处理打印时，问卷数据
     */
    var printQuestData = function (list) {
        var arr = []
        for (var i = 0; i < list.length; i++) {
            if (list[i].children) {
                var obj = {}
                obj.children = printQuestData(list[i].children)
                if (obj.children.length > 0) {
                    if (list[i].label) obj.label = list[i].label
                    if (list[i].type) obj.type = list[i].type
                    if (list[i].followupGuidance) global_followupGuidance = list[i].followupGuidance
                    arr.push(obj)
                }
            } else {
                if (list[i].id && list[i].val) {
                    var obj = {}
                    obj.id = list[i].id
                    obj.label = list[i].label
                    obj.type = list[i].type
                    if (jQuery.isArray(list[i].val)) {
                        var str = ''
                        for (var j = 0; j < list[i].val.length; j++) {
                            if (obj.type == "question_multiSelect" || obj.type == "question_multiText") {
                                for (var j = 0; j < list[i].list.length; j++) {
                                    if (list[i].list[j].val) {
                                        if (list[i].order && list[i].order == "reversed") {
                                            str += list[i].list[j].subunit + list[i].list[j].val + "、"
                                        } else {
                                            str += list[i].list[j].val + list[i].list[j].subunit
                                        }
                                    }
                                }
                            } else if (obj.type == "question_multiTextSelect") {
                                str += list[i].val[j]
                            } else if (obj.type == "question_multiLabelText" || obj.type == "question_uploadPictures" || obj.type == "question_sudokuPictures") {
                                str = list[i].val
                            } else {
                                if (str == "") {
                                    str += list[i].val[j]
                                } else {
                                    str += "、" + list[i].val[j]
                                }
                            }
                        }
                        obj.val = str
                    } else {
                        obj.val = list[i].val
                    }
                    arr.push(obj)
                }
            }
        }
        return arr
    }
    /**
     * 处理打印时，问卷数据
     */
    servers.handlePrintQuest = function (data) {
        if (data.questiones && data.values) {	// 配置了问卷的情况
            var arr = $questionServers.getQuestionData({
                list: data.questiones,	  // 问卷
                values: data.values,	// 问卷答案
            }).questions
            var arrPrint = []
            for (var i = 0; i < arr.length; i++) {
                arrPrint.push(printQuestData(arr[i]))
            }
            return {
                "questionsPrint": arrPrint,
                "followupGuidance": global_followupGuidance,
            }
        }
    }
    /**
     * 处理打印时，需要的患随访指导信息
     */
    servers.handlePrintTask = function (task) {
        var data = {}
        var d = new Date()
        //d.setTime(creatTime);
        var getMonth = d.getMonth() + 1
        var date = d.getFullYear() + "-" + getMonth + "-" + d.getDate() + " "
        var minutes = d.getMinutes();
        (minutes >= 10) ? minutes : minutes = "0" + minutes
        var myDate = date + d.getHours() + ":" + minutes  //获取日期与时间
        data['myDate'] = myDate
        for (var key in task) {
            if (key == "nextAddress") {
                data[key] = task[key][0]
            } else if (key == "finishDate" || key == "finishTime" || key == "taskNote") {
                data[key] = task[key]
            } else if (key == "updateAuname") {
                data[key] = task[key]
            } else if (key == "nextDateTime") {
                data[key] = task[key]
            }
        }
        return data
    }
    /**
     * 处理打印时，需要的患者信息
     */
    servers.handlePatientInfo = function (data) {
        var info = {}
        var tenant_name = $(".tenant_name").text()
        if (tenant_name == "眼保健专科管理系统") {
            tenant_name = "儿童眼保健"
        } else {
            tenant_name = "随访"
        }
        info["tenant_name"] = tenant_name
        for (var key in data) {
            if (key == "gender") {
                info[key] = data[key] == 'F' ? '女' : '男'
            } else {
                info[key] = data[key]
            }
        }
        return info
    }
    /**
     * 获取打印时需要的医院信息（医院名字、科室名字）
     */
    servers.handlePrintHospital = function (info, quest, callback, printTemState) {
        $bb.ajax({
            url: URL + "followup/service/patientFollow/queryHospitalInfo",
            success: function (data) {
                if (data.success) {
                    callback(data.data, info, quest, printTemState)
                } else {
                    $bb.toastShow(data.msg ? data.msg : "查询医院信息出错！")
                }
            }
        })
    }
    /**
     * 获取删除患者时的参数
     */
    servers.getDeleteParams = function () {
        var params = $bb.getPageParams()
        var deleteParams = {
            oprInfo: {
                opCode: "1017",
                opNote: "【" + sessinonUserName + "】医生将【" + params.patientName + "】患者从" + params.queuename + "中删除",
                opType: "2",
            },
            patientInfo: {
                followQueueId: params.followQueueId,
                patientId: params.patientId,
                ptSchemeId: params.patientSchemeId,
            },
        }
        return deleteParams
    }
    /**
     * 获取请求任务列表时的参数
     */
    var getTasksParams = function () {
        var params = $bb.getPageParams()
        return {
            "patientSchemeId": params.patientSchemeId,
            "followQueueId": params.followQueueId
        }
    }
    /**
     * 获取当前任务的索引号（根据当前任务id和任务列表数据）
     */
    servers.getTaskIndexByTaskId = function (rows, taskId) {
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].taskId == taskId) {
                var index = i
                break
            }
        }
        return index
    }
    /**
     * 获取随访任务状态中是否有还未进行的任务（目的：若没有，则添加“添加随访”按钮）
     */
    servers.getAddTaskInfo = function (rows) {
        var addTaskFlag = true
        var afterTaskId = rows[rows.length - 1].taskId
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].taskStatus == "0") {
                addTaskFlag = false
                break
            }
        }
        return {"addTaskFlag": addTaskFlag, "afterTaskId": afterTaskId}
    }
    /**
     * 获取保存问卷时，所需的参数
     */
    var getSaveParams = function (data, params) {
        var defaults = {
            ptContentIds: data.task.ptContentIds,
            ptTaskId: data.task.ptTaskId,
            ptTaskName: data.task.ptTaskName,
            seqNo: data.task.seqNo
        }
        var domId = $("#followUpInfo form").attr("id")

        //wxf 生长发育数据打通
        //calctype     00001   体重(g)
        //calctype     00002   身长(cm)
        //calctype     00003   头围(cm)：
        if ($("#" + domId + " input[calctype=00002]").attr("name") != undefined) {
            var weightName = $("#" + domId + " input[calctype=00001]").attr("name").split("-g")[0]
            var heightName = $("#" + domId + " input[calctype=00002]").attr("name")
            var headCircumName = $("#" + domId + " input[calctype=00003]").attr("name")
            var testTime = $("input[name=finishDate]").val()
        }
        var questiones = $questionServers.getDataForDom(domId)
        //根据问卷的name取问卷对象值
        var paramsRecord = {}
        if (questiones.hasOwnProperty(weightName)) {
            if (questiones[weightName] != "") {
                paramsRecord.weight = questiones[weightName]
                paramsRecord.testTime = testTime
            }
            if (questiones[heightName] != "") {
                paramsRecord.height = questiones[heightName]
                paramsRecord.testTime = testTime
            }
            if (questiones[headCircumName] != "") {
                paramsRecord.headCircumference = questiones[headCircumName]
                paramsRecord.testTime = testTime
            }
        } else {
            paramsRecord = {}
        }


        var task = $.extend(defaults, getDataTask("followUpInfo"))
        var sampleList = getDataSampleList("followUpInfo")
        var params = {
            oprInfo: {
                followQueueId: data.oprInfo.followQueueId,
                opCode: "1001",
                opNote: "【" + sessinonUserName + "】医生为【" + params.patientName + "】患者进行" + data.task.ptTaskName + "修改",
                opType: "2",
                sourceType: "2",
                patientId: data.oprInfo.patientId,
                ptSchemeId: data.oprInfo.ptSchemeId,
            },
            questiones: questiones,
            task: task,
            paramsRecord: paramsRecord   //wxf 生长发育数据打通
        }
        var config = $root.init()
        if (config.dom.outPatientCollect) {
            params = $.extend(params, {sampleList: sampleList})
        }
        return params
    }
    /**
     * 处理[任务列表]数据
     */
    servers.handleTasks = function (list, taskId) {
        var arr = []
        for (var i = 0; i < list.length; i++) {
            arr[i] = list[i]
            if (i > 0) arr[i].preTaskId = arr[i - 1].taskId
            if (taskId) {
                arr[i].currentTaskFlag = false
                if (arr[i].taskId == taskId) {
                    arr[i].currentTaskFlag = true
                }
            }
            arr[i].taskDate = list[i].taskDate		// 将年份保留
        }
        return arr
    }
    /**
     * 请求任务列表
     */
    servers.ajaxTasks = function (callback, params) {
        $bb.ajax({
            url: URL + "followup/service/patient/patientTaskListQuery",
            data: JSON.stringify({
                data: getTasksParams()
            }),
            success: function (data) {
                if (data.success) {
                    callback(data.data.rows, params)
                } else {
                    $bb.toastShow(data.msg ? data.msg : "随访任务列表加载失败！")
                }
            }
        })
    }
    /**
     * 请求问卷
     */
    servers.ajaxQuestion = function (params, curInfo, callback, addTaskInfo) {
        $bb.ajax({
            url: URL + "followup/service/patient/patientTaskContentDataQuery",
            data: JSON.stringify({
                data: {
                    followQueueId: params.followQueueId,
                    ptTaskId: curInfo.taskId
                }
            }),
            success: function (data) {
                if (params.followQueueId == "duiLie_naocuzhong"){
                    if (data.success) {
                        if (data.data.physique && data.data.physique["bodyMassIndex"]) {
                            var {height, weight, bodyMassIndex} = data.data.physique
                            data.data.values["Height"] = height
                            data.data.values["Weight"] = weight
                            data.data.values["BodyMassIndex"] = bodyMassIndex.toFixed(2)
                        }
                        if (!data.data.values["ncz_zywxys"]) {
                            if (data.data.nirnAssessData) {
                                var {riskFactors} = data.data.nirnAssessData
                                data.data.values["ncz_zywxys"] = riskFactors
                            }
                        }
                        if (!data.data.values["scaleAssessStatus"]) {
                            if (data.data.nirnAssessData) {
                                var {guide} = data.data.nirnAssessData
                                data.data.values["scaleAssessStatus"] = guide.replace('<b style="color:red;font-size:20px">',"").replace("</b>","")
                            }
                        }
                        data.data.task.finishDate = data.data.task.finishDate == '' ? null : data.data.task.finishDate
                        data.data.task.finishTime = data.data.task.finishTime == '' ? null : data.data.task.finishTime
                        callback(data.data, params, curInfo, addTaskInfo)
                    } else {
                        $bb.toastShow(data.msg ? data.msg : "随访问卷加载失败！")
                    }

                }else {
                    if (data.success){

                        callback(data.data, params, curInfo, addTaskInfo)
                    } else {
                        $bb.toastShow(data.msg ? data.msg : "随访问卷加载失败！")
                    }

                }

            }
        })
    }
    /**
     * 根据母亲手机号请求数据
     */
    servers.ajaxQueryFamilyInfo = function (followQueueId, phone, callback) {
        // console.log('params', followQueueId)
        $bb.ajax({
            url: URL + "/followup/gy3y/queryFamilyInfo",
            data: JSON.stringify({
                data: {
                    queueId: followQueueId,
                    phone: phone
                }
            }),
            success: function (data) {
                if (data.success) {
                    callback(data.data)
                } else {
                    $bb.toastShow(data.msg ? data.msg : "请求失败！")
                }
            }
        })
    }
    /**
     * 添加随访
     */
    servers.ajaxAddTask = function (data) {
        console.log(data)
        var params = data.params
        var callback = data.fun
        var getTasksCallback = data.getTasksCallback
        $bb.ajax({
            url: URL + "followup/service/patient/addTempTask",
            data: JSON.stringify({
                data: {
                    "oprInfo": {
                        "opCode": "1018",
                        "opNote": "【" + sessinonUserName + "】医生给【" + params.patientName + "】患者新增了临时随访任务",
                        "opType": "2",
                    },
                    "taskInfo": {
                        "followQueueId": params.followQueueId,
                        "patientId": params.patientId,
                        "ptSchemeId": params.patientSchemeId,
                        "ptTaskId": data.afterTaskId,
                        "executeTime": data.executeTime,
                        "actualAge": data.actualAge
                    }
                }
            }),
            success: function (data) {
                if (data.success) {
                    $bb.toastShow("添加临时随访任务成功！")
                    params.taskId = data.data.newTaskId
                    callback(getTasksCallback, params)
                } else {
                    $bb.toastShow(data.msg ? data.msg : "添加临时随访任务失败！")
                }
            }
        })
    }
    servers.ajaxUpDateTask = function (params, callback) {
        $bb.ajax({
            url: URL + 'followup/service/patient/updateTempTask',
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if (data.success) {
                    $bb.toastShow(data.data.msg)
                    callback()
                } else {
                    $bb.toastShow("修改临时随访任务失败!")
                }
            }
        })
    }
    /**
     * [问卷]提交
     */
    servers.ajaxSaveQuestion = function (data1, params, curInfo, callback) {
        $bb.ajax({
            url: URL + "followup/service/patient/patientTaskContentDataModify",
            data: JSON.stringify({
                data: getSaveParams(data1, params)
            }),
            success: function (data) {
                if (data.success) {
                    callback(params, curInfo, getSaveParams(data1, params).paramsRecord)
                } else {
                    $bb.toastShow(data.msg ? data.msg : "保存失败！", 3000)
                }
            }
        })
    }
    /**
     * 删除患者
     */
    servers.ajaxDelPatient = function (params) {
        $bb.ajax({
            url: URL + "followup/service/patient/history/patientDel",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if (data.success) {
                    var config = $root.init()
                    $bb.toastShow("删除成功！", 2000, $bb.openPage, config.route.outPatientDelPatient)
                } else {
                    $bb.toastShow(data.msg ? data.msg : "删除失败！")
                }
            }
        })
    }
    /**
     * 删除临时随访问卷
     */
    servers.ajaxDeleteTemporary = function (data) {
        var params = data.params
        $bb.ajax({
            url: URL + "followup/service/patient/delTempTask",
            data: JSON.stringify({
                data: {
                    "oprInfo": {
                        "opCode": "1020",
                        "opNote": "【" + sessinonUserName + "】医生给【" + params.patientName + "】患者删除了临时随访任务",
                        "opType": "2",
                    },
                    "taskInfo": {
                        "followQueueId": params.followQueueId,
                        "patientId": params.patientId,
                        "ptSchemeId": params.patientSchemeId,
                        "ptTaskId": data.taskId
                    }
                }
            }),
            success: function (result) {
                if (result.success) {
                    $bb.toastShow("删除成功！")
                    data.fun(data.deleteTasksCallback, params)
                } else {
                    $bb.toastShow(result.msg ? result.msg : "删除失败！")
                }
            }
        })
    }
    /**
     *    获取任务状态（根据任务状态码）
     */
    var curTaskStatus = function (status) {
        if (status == "0") {
            status = "default"
        } else if (status == "1") {
            status = "readonly"
        } else if (status == "2") {
            status = "disabled"
        }
        return status
    }
    servers.curTaskStatus = function (status) {
        return curTaskStatus(status)
    }
    /**
     * 获取当前任务信息
     */
    servers.getCurInfo = function (rows, taskId) {
        var str = ""		// 当前的任务id
        var status = ""	// 当前的任务status
        var seqNo = ""		// 当前的任务seqNo
        var preTaskId = ""		// 上一次的任务seqNo
        var taskStatus = ""	// 当前的任务taskStatus(打印问卷时判断是否显示打印按钮)
        var auditStatus = ""   // 当前任务审核状态
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].currentTaskFlag == true) {
                str = rows[i].taskId
            }
        }
        if (str == "") {
            str = rows[0].taskId
        }
        if (taskId) {	// 从随访记录中跳过来，带过来的 taskId
            str = taskId
        }
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].taskId == str) {
                taskStatus = rows[i].taskStatus
                status = curTaskStatus(rows[i].taskStatus)
                seqNo = rows[i].seqNo
                if (i > 0) preTaskId = rows[i - 1].taskId
                auditStatus = rows[i].auditStatus
            }
        }
        return {
            "taskId": str,
            "status": status,
            "seqNo": seqNo,
            "preTaskId": preTaskId,
            "taskStatus": taskStatus,
            "auditStatus": auditStatus
        }
    }
    /**
     * [随访指导]随访年龄数据处理
     */
    var getFollowupAge = function (params, finishDate) {
        var actualDays = $comm.dateDiff(params.birthday, finishDate).days
        var actualAge = $comm.dateDiff(params.birthday, finishDate).age
        var age, ageLabel
        if (params.expectedDay) {
            var correctDays = $comm.dateDiff(params.expectedDay, finishDate).days
            // 2岁内的早产儿用纠正年龄(孕周小于37周为早产儿)
            if (params.pregnancyDay < 37 * 7 && actualDays < 365 * 2) {
                if (correctDays < 0) {
                    var days = correctDays + 40 * 7
                    var week = parseInt(days / 7)
                    var day = parseInt(days % 7)
                    age = week + "周" + day + "天"
                    ageLabel = "纠正胎龄"
                } else {
                    var correctAge = $comm.dateDiff(params.expectedDay, finishDate).age
                    age = correctAge
                    ageLabel = "纠正年龄"
                }
                return {
                    "age": age,
                    "ageLabel": ageLabel,
                    "actualAge": actualAge,
                    "actualAgeLabel": "实际年龄"
                }
            } else {
                age = actualAge
                ageLabel = "实际年龄"
            }
        } else {
            age = actualAge
            ageLabel = "实际年龄"
        }
        return {
            "age": age,
            "ageLabel": ageLabel
        }
    }
    servers.getFollowupAge = function (params, finishDate) {
        return getFollowupAge(params, finishDate)
    }
    /**
     * [随访指导]数据处理
     */
    var taskData = function (task, ageRelate, status) {
        var data = $.extend({}, task)
        // data.nextTime为处理后的下次随访时间
        var config = $root.init()
        data.nextTime = config.dom.outPatientNextTimeValue ? data.nextDate[0] : data.nextDateTime
        for (var key in data) {
            if (key == "finishDate" && status == "default") {
                if (!data[key]) {
                    if (data.taskStatus == "0") {
                        data[key] = $comm.getCurTime().date
                    } else if (data.taskStatus == "2") {
                        data[key] = data.taskDate
                    }
                }
            } else if (key == "updateAuname" && status == "default") {
                data[key] = sessinonUserName
            }
        }
        if (data.finishDate != null) { // 有随访时间就有随访年龄
            var ageObj = getFollowupAge(ageRelate, data.finishDate)
            data.followupAge = ageObj.age
            data.followupAgeLabel = ageObj.ageLabel
            if (ageObj.actualAge && ageObj.actualAgeLabel) {
                data.followupActualAge = ageObj.actualAge
                data.followupActualAgeLabel = ageObj.actualAgeLabel
            }
        } else {
            data.followupAgeLabel = "实际年龄"
        }
        if (data.followupActualAge && data.followupActualAgeLabel) {
            data.length = 3
        } else {
            data.length = 4
        }
        return data
    }
    /**
     * 安医大采集数据处理
     */
    var samplesData = function (sampleList, status) {
        var arr = []
        if (sampleList && jQuery.isArray(sampleList)) {
            var labelArr1 = ["尿液", "血液", "唾液", "头发"]
            var labelArr2 = ["第1次", "第2次", "第3次"]
            var nameArr1 = ["urine", "blood", "saliva", "hair"]
            var nameArr2 = ["1", "2", "3"]
            var list = [
                {
                    key: "0",
                    value: "未采集"
                },
                {
                    key: "1",
                    value: "已采集"
                }
            ]
            for (var i = 0; i < sampleList.length; i++) {
                for (var j = 0; j < 3; j++) {
                    var obj = {}
                    obj.status = status
                    obj.sampleType = sampleList[i].sampleType
                    obj.label = labelArr1[i] + labelArr2[j]
                    obj.name = nameArr1[i] + nameArr2[j]
                    obj.val = j == 0 ? sampleList[i].sampleValue1 : j == 1 ? sampleList[i].sampleValue2 : sampleList[i].sampleValue3
                    if (obj.val == "") obj.val = "0"
                    obj.list = list
                    arr.push(obj)
                }
            }
        }
        var config = $root.init()
        var data = {
            sampleList: arr,
            flag: config.dom.outPatientCollect
        }
        return data
    }
    /**
     * 问卷里若有题型里有followupGuidance字段，则写死的“随访指导”不显示,返回false；若没有，则显示返回true。
     */
    var getFlagTaskGuide = function (list) {
        for (var i = 0; i < list.length; i++) {
            if (list[i].followupGuidance) {
                return false
            }
            if (list[i].children) {
                getFlagTaskGuide(list[i].children)
            }
        }
        return true
    }
    /**
     * 随访问卷task数据处理
     */
    servers.handleFollowupTask = function (options) {
        var defaults = {
            status: "default",
            showIcon: false
        }
        var opts = $.extend(defaults, options)
        var task = $.extend(defaults, taskData(opts.task, opts.ageRelate, opts.status))
        var flag = (opts.list && jQuery.isArray(opts.list)) ? true : false
        var sampleList = samplesData(opts.sampleList, opts.status)
        var flagTaskGuide
        for (var i = 0; i < options.list.length; i++) {
            flagTaskGuide = getFlagTaskGuide(options.list[i])
            if (!flagTaskGuide) break
        }
        var config = $root.init()
        flagTaskGuide = flagTaskGuide && config.dom.outPatientTaskGuide
        var data = {
            status: task.status,
            flagQuestions: flag,		// 是否配置了问卷
            task: task,		// 随访备注
            sampleList: sampleList,	// 安医大采集
            flagTaskGuide: flagTaskGuide // 随访指导展示与否
        }
        return data
    }
    /**
     * 随访问卷提交时，获取task数据
     */
    var getDataTask = function (domId) {	// domId:整个问卷加随访备注的外裹domId
        var data = {}
        data.finishDate = $("#" + domId + " input[name='finishDate']").val()
        data.nextDate = $("#" + domId + " input[name='nextDate']").val()
        data.nextAddress = $("#" + domId + " select[name='nextAddress']").val()
        data.updateAuname = $("#" + domId + " p[name='updateAuname']").text()
        data.followupAge = $("#" + domId + " p[name='followupAge']").text()
        data.taskNote = $("#" + domId + " textarea[name='taskNote']").val()
        return data
    }
    /**
     * 随访问卷提交时，获取sampleList数据
     */
    var getDataSampleList = function (domId) {	// domId:整个问卷的外裹domId
        var arr = []
        var nameArr1 = ["urine", "blood", "saliva", "hair"]
        var nameArr2 = ["1", "2", "3"]
        var typeArr = ["0", "1", "2", "3"]
        for (var i = 0; i < nameArr1.length; i++) {
            var obj = {}
            obj.sampleCode = "bioSample"
            obj.sampleType = typeArr[i]
            obj.sampleValue1 = ""
            obj.sampleValue2 = ""
            obj.sampleValue3 = ""
            for (var j = 0; j < nameArr2.length; j++) {
                var name = nameArr1[i] + nameArr2[j]
                var value = $("#" + domId + " select[name='" + name + "']").val()
                if (j == 0) obj.sampleValue1 = value
                if (j == 1) obj.sampleValue2 = value
                if (j == 2) obj.sampleValue3 = value
            }
            arr.push(obj)
        }
        return arr
    }
    /**
     * 处理btnGroup数据
     */
    servers.handleBtnGroup = function (params, params0) {
        // console.log(params0)
        var config = $root.init()
        $.extend(params, {"showAddTaskBtn": config.dom.outPatientAddTaskBtn})
        var topbars = []
        if (window.__config__.role.indexOf('ReadOnly') == -1) {
            if (params.status == "default") {
                topbars.push({
                    "icon": "fa fa-floppy-o",
                    "name": "保存记录",
                    "callback": params0.callback2,
                    "params": params0.params2
                })
                if (params0.params7.params.followQueueId == "12gfyxsekqueue001") {
                    topbars.push({
                        "icon": "fa fa-trash-o",
                        "name": "清除内容",
                        "callback": params0.callback7,
                        "params": params0.params7
                    })
                }
            } else if (params.status == "readonly" || params.status == "disabled") {
                var obj = {
                    "icon": "fa fa-pencil-square-o",
                    "name": "修改记录",
                    "callback": params0.callback3,
                    "params": params0.params3
                }
                topbars.push(obj)
            }

            if (params.isTemporary) {
                var obj = {
                    "icon": "fa fa-trash-o",
                    "name": "删除临时随访",
                    "callback": params0.callback8,
                    "params": params0.params8
                }
                topbars.push(obj)
            }
            if (params.addTaskFlag) {
                if (params.showAddTaskBtn) {
                    var obj = {
                        "icon": "fa fa-plus-square-o",
                        "name": "临时随访",
                        "callback": params0.callback4,
                        "params": params0.params4
                    }
                    topbars.push(obj)
                }
            }
            topbars.push({
                "icon": "fa fa-trash-o",
                "name": "删除患者",
                "callback": params0.callback1,
                "params": params0.params1
            })
            /**
             * 2020 10 31
             * 关联其他队列患者
             */
            if (window.__config__.__is_show_relation__) {
                topbars.push({
                    "icon": "fa fa-chain",
                    "name": "关联其他队列",
                    "callback": params0.callback11,
                    "params": params0.params11
                })
            }

            // 出院小结
            if (config.dom.outPatientDischargeSummary) {
                topbars.push({
                    "icon": "fa fa-picture-o",
                    "name": "出院小结",
                    "callback": params0.callback9,
                    "params": params0.params9
                })
            }
            if (params.auditStatus == "4") {
                var obj = {
                    "icon": "fa fa-calendar-check-o",
                    "name": "审核通过",
                    "callback": params0.callback6,
                    "params": params0.params6
                }
                topbars.push(obj)
            }
            topbars.push({
                icon: "fa fa-minus-circle",
                name: '终止随访',
                callback: params0.callback16,
                params: params0.params16
            })
        }


        if (params.seqNo != 0) {
            if (params.taskStatus == "1" || params.taskStatus == "2") {
                var obj = {
                    "icon": "fa fa-print",
                    "name": "打印(病历本)",
                    "callback": params0.callback5,
                    "params": params0.params5
                }
                topbars.push(obj)
            }
        }
        /**
         * wxf 20190717新加打印模板
         */
        if (params.seqNo != 0) {
            if (params.taskStatus == "1" || params.taskStatus == "2") {
                var obj = {
                    "icon": "fa fa-print",
                    "name": "打印(纸质单)",
                    "callback": params0.callback10,
                    "params": params0.params10
                }
                topbars.push(obj)
            }
        }
        /**
         * wxf 20190717新加打印模板
         */
        if (params.seqNo != 0) {
            if (params.taskStatus == "1" || params.taskStatus == "2") {
                var obj = {
                    "icon": "fa fa-print",
                    "name": "打印报告单",
                    "callback": params0.callback17,
                    "params": params0.params17
                }
                topbars.push(obj)
            }
        }
        /**
         * 2020 11 12 新增建档打印功能
         * @params.seqNo 未知意义，但是每一列安此递增
         * 故判断为 0 时是建档信息
         */
        if (params.seqNo == 0) {
            topbars.push({
                "icon": "fa fa-print",
                "name": "建档打印",
                "callback": params0.callback12,
                "params": params0.params12
            })
        }

        /**
         * 2021 4 7 新增预约标记菜单
         * @params.seqNo 为最后一个才可以添加预约
         * 2021 4 12 根据菜单配置判断是否显示
         *        # 如果存在 appointment_status
         *        # appointment_status 的值为 1 或 数组时显示该预约
         */
        if (window.__global__.appointment_status) {
            var status = window.__global__.appointment_status
            if (status === '1' || status === 1) {
                showAppointment()
            } else if (Object.prototype.toString.call(status) === '[object Array]') {
                if (status.indexOf(params0.params13.params.followQueueId) > -1) {
                    showAppointment()
                }
            }
        }

        function showAppointment() {
            var moduleLength
            try {
                moduleLength = document
                    .getElementsByClassName('show-wrapper ')[0]
                    .getElementsByClassName('row')
                    .length
            } catch (err) {
                moduleLength = 0
            }
            if (moduleLength - 1 == params.seqNo) {
                topbars.push({
                    icon: "fa fa-address-card-o",
                    name: "标记预约",
                    callback: params0.callback13,
                    params: params0.params13
                })
            }
            topbars.push({
                icon: "fa fa-table",
                name: "预约详情",
                callback: params0.callback14,
                params: params0.params14
            })
        }

        /**
         * 2021 4 28
         * 照片分享
         */
        if (window.__global__.Photo_sharing) {
            // console.log('params0', params0)
            var status = window.__global__.Photo_sharing
            if (status === '1' || status === 1) {
                showPhotoSharing()
            } else if (Object.prototype.toString.call(window.__global__.Photo_sharing) === '[object Array]') {
                if (window.__global__.Photo_sharing.indexOf(params0.params15.params.followQueueId) > -1) {
                    showPhotoSharing()
                }
            }
        }

        function showPhotoSharing() {
            topbars.push({
                icon: "fa fa-camera",
                name: "照片分享",
                callback: params0.callback15,
                params: params0.params15
            })
        }


        return topbars
    }

    /**
     * 获取对应锚点的id
     */
    var handle = function (arr, newArr) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].type == "qusetion_groupCollapse" || arr[i].type == "qusetion_group" || arr[i].type == "qusetion_groupTable") {
                newArr.push(arr[i])
            }
        }
        return newArr
    }

    /**
     * 获取锚点nav的数据
     */
    servers.handleAnchorMenu = function (list) {
        var newArr = []
        for (var i = 0; i < list.length; i++) {
            handle(list[i], newArr)
        }
        return newArr
    }

    /**
     * 请求绑定在该患者身上的图片
     */
    servers.ajaxNffyyFile = function (params, callback, className) {
        $bb.ajax({
            url: URL2 + "imgCollection/imgMark/queryNffyyFile",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                callback(data, params, className)
            }
        })
    }

    /**
     * 根据文件的一个地址请求文件的另一个地址
     */
    servers.ajaxImgFileSignUrl = function (params, callback, arg, total, className) {
        $bb.ajax({
            url: URL2 + "imgCollection/imgMark/getImgFileSignUrl",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if (data.success) {
                    callback(data.data, arg, total, className)
                } else {
                    $bb.toastShow(data.msg ? data.msg : "请求文件地址出错！")
                }
            }
        })
    }

    /**
     * wxf随访生长发育和量表生长发育打通
     */
    servers.addGrowthANDRecord = function (userId, params) {
        // console.log('params888', params)
        if (userId) {
            var height = params.height
            var weight = params.weight
            var headCircumference = params.headCircumference
            $bb.ajax({
                url: URL + "followup/service/patient/growth/addGrowthRecord",
                type: "post",
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
                data: JSON.stringify({
                    data: params
                }),
                success: function (data) {
                    if (data.success) {
                        var growthRecordId = data.data.id
                        var obj = {
                            "growthRecordId": growthRecordId,
                            "userId": userId
                        }
                        //$bb.openPage("growthDevelopmentDetails",obj);
                    }
                },
                error: function (data) {
                }
            })
        } else {
            $bb.toastShow("请先查询选择需要上传的用户！！！", 1500)
        }
    }

    /**
     * @title 查找可加入的队列
     * @param param { object }
     * @param callback { function }
     */
    servers.getQueryQueue = function (params, callback) {
        $bb.ajax({
            url: URL + 'followup/service/patientSwitch/queryQueue',
            type: 'post',
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if (data.success) {
                    callback(data.data, params)
                } else {
                    $bb.toastShow(data.msg ? data.msg : "查询可加入的队列出错！")
                }
            }
        })
    }

    /**
     * @title 讲患者复制到对应队列
     *
     */
    servers.copyPatient = function (params, callback) {
        $bb.ajax({
            url: URL + 'followup/service/patientSwitch/copyPatient',
            type: 'post',
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if (data.success) {
                    callback(data.data)
                } else {
                    $bb.toastShow(data.msg ? data.msg : "复制患者出错！")
                }
            }
        })
    }

    /**
     * 标记预约
     * @param {*} params
     * @param {*} callback
     */
    servers.markAppointment = function (params, callback) {
        $bb.ajax({
            url: URL + 'followup/appointment/record/mark',
            type: 'post',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(params),
            success: function (res) {
                callback(res)
            }
        })
    }

    /**
     * 结案
     * @param {} patId
     * @param {*} callback
     */
    servers.queryClosedRecord = function (patId, callback) {
        $bb.ajax({
            url: URL + 'followup/service/patient/queryClosedRecord',
            type: 'post',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify({
                data: {
                    patientId: patId
                }
            }),
            success: function (res) {
                callback(res)
            }
        })
    }

    /**
     * 获取个人预约详情
     * @param {*} params
     * @param {*} callback
     */
    servers.getAppointmentDetail = function (params, callback) {
        /*
        $bb.ajax({
            url: URL + 'followup/appointment/record/detailList',
            type: 'post',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(params),
            success: function (res) {
                callback(res)
            }
        })
        */
    }


    return servers
})
